import React, { Component } from 'react'
import './index.css'

const MyContext = React.createContext()
const { Provider, Consumer } = MyContext
export default class A extends Component {
  state = { username: 'tom', age: 18 }
  render() {
    const { username, age } = this.state
    return (
      <div className='parent'>
        <h1>我是A组件</h1>
        <h4>我的用户名是：{username}</h4>
        <h4>我的年龄是：{age}</h4>
        <Provider value={{ username, age }}>
          <B />
        </Provider>
      </div>
    )
  }
}

class B extends Component {
  render() {
    return (
      <div className='child'>
        <h1>我是B组件</h1>
        <h4>我从A组件接收到的用户名是：</h4>
        <h4>我从A组件接收到的年龄是：</h4>
        <C />
      </div>
    )
  }
}

/* class C extends Component {
  // 声明接收context
  static contextType = MyContext
  render() {
    const { username, age } = this.context
    return (
      <div className='grand'>
        <h1>我是C组件</h1>
        <h4>我从A组件接收到的用户名是：{username}</h4>
        <h4>我从A组件接收到的年龄是：{age}</h4>
      </div>
    )
  }
}
 */

function C() {
  return (
    <div className='grand'>
      <h1>我是C组件</h1>
      <Consumer>
        {/* {value=>{
          return `${value.username}，年龄是：${value.age}`
        }} */}
        {/* {({username,age})=>{
          return `${username}，年龄是：${age}`
        }} */}
        {({ username, age }) => {
          return (<div>
            <h4>我从A组件接收到的用户名是：{username}</h4>
            <h4>我从A组件接收到的年龄是：{age}</h4>
          </div>)
        }}
      </Consumer>
    </div>
  )
}
